import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:fluttertoast/fluttertoast.dart';

import '../../common/index.dart';
import '../../config/index.dart';

import '../../tools/shared_preferences_tool.dart';

/// 登录页面控制器
class LoginController extends BaseGetXController {
  /// 用户名输入控制器
  final TextEditingController usernameController = TextEditingController();

  /// 密码输入控制器
  final TextEditingController passwordController = TextEditingController();

  /// 是否隐藏密码
  final RxBool isPasswordHidden = true.obs;

  /// 是否记住密码
  final RxBool isRememberPassword = false.obs;

  /// 是否正在加载
  final RxBool isLoading = false.obs;

  @override
  void onInit() {
    super.onInit();
    _loadSavedCredentials();
  }

  @override
  void onClose() {
    usernameController.dispose();
    passwordController.dispose();
    super.onClose();
  }

  /// 加载保存的凭据
  void _loadSavedCredentials() {
    final loginInfo = SharedPreferencesTool.getLoginInfo();
    final savedUsername = loginInfo['username'] as String?;
    final savedPassword = loginInfo['saved_password'] as String?;
    final rememberPassword = loginInfo['remember_password'] as bool?;

    if (savedUsername != null && savedUsername.isNotEmpty) {
      usernameController.text = savedUsername;
    }

    if (rememberPassword == true &&
        savedPassword != null &&
        savedPassword.isNotEmpty) {
      passwordController.text = savedPassword;
      isRememberPassword.value = true;
    }
  }

  /// 切换密码可见性
  void togglePasswordVisibility() {
    isPasswordHidden.value = !isPasswordHidden.value;
  }

  /// 切换记住密码
  void toggleRememberPassword(bool? value) {
    isRememberPassword.value = value ?? false;
  }

  /// 登录按钮点击事件
  Future<void> onLoginTap() async {
    final username = usernameController.text.trim();
    final password = passwordController.text.trim();

    // 验证输入
    if (username.isEmpty) {
      Fluttertoast.showToast(msg: '请输入用户名');
      return;
    }

    if (password.isEmpty) {
      Fluttertoast.showToast(msg: '请输入密码');
      return;
    }

    if (password.length < 6) {
      Fluttertoast.showToast(msg: '密码长度不能少于6位');
      return;
    }

    try {
      isLoading.value = true;

      // 模拟网络延迟
      await Future.delayed(const Duration(milliseconds: 800));

      // 本地验证逻辑 - 预设测试账号
      final validAccounts = {
        'admin': '123456',
        'doctor': '123456',
        'nurse': '123456',
        'test': '123456',
        'demo': '123456',
      };

      bool isValidLogin = false;
      Map<String, dynamic>? userInfo;

      // 检查预设账号
      if (validAccounts.containsKey(username) &&
          validAccounts[username] == password) {
        isValidLogin = true;
        // 生成预设账号的用户信息
        userInfo = {
          'id': 'user_${username}_${DateTime.now().millisecondsSinceEpoch}',
          'username': username,
          'nickname': _getNicknameByUsername(username),
          'avatar': 'https://api.dicebear.com/7.x/avataaars/svg?seed=$username',
          'phone':
              '138****${(1000 + (username.hashCode % 9000)).toString().substring(1)}',
          'email': '$username@medical.com',
          'department': _getDepartmentByUsername(username),
          'position': _getPositionByUsername(username),
          'createTime': DateTime.now().toIso8601String(),
        };
      } else {
        // 检查注册用户
        final registeredUsers =
            SharedPreferencesTool.getStringList('registered_users') ?? [];
        if (registeredUsers.contains(username)) {
          final savedPassword =
              SharedPreferencesTool.getString('user_password_$username');
          if (savedPassword == password) {
            isValidLogin = true;
            // 从本地存储获取用户信息
            final userInfoStr =
                SharedPreferencesTool.getString('user_info_$username');
            if (userInfoStr != null) {
              userInfo = jsonDecode(userInfoStr);
            }
          }
        }
      }

      if (isValidLogin && userInfo != null) {
        final token =
            'token_${username}_${DateTime.now().millisecondsSinceEpoch}';

        // 保存用户信息到本地存储
        await SharedPreferencesTool.saveLoginInfo(
          username: username,
          userId: userInfo['id']!,
          token: token,
          password: isRememberPassword.value ? password : null,
          rememberPassword: isRememberPassword.value,
        );
        await SharedPreferencesTool.saveUserInfo(userInfo);

        Fluttertoast.showToast(msg: '登录成功');

        // 跳转到主页面
        Get.offAllNamed(RouterIdConfig.root);
      } else {
        Fluttertoast.showToast(msg: '用户名或密码错误');
      }
    } catch (e) {
      debugPrint('登录失败: $e');
      Fluttertoast.showToast(msg: '登录失败，请重试');
    } finally {
      isLoading.value = false;
    }
  }

  /// 根据用户名获取昵称
  String _getNicknameByUsername(String username) {
    switch (username) {
      case 'admin':
        return '系统管理员';
      case 'doctor':
        return '张医生';
      case 'nurse':
        return '李护士';
      case 'test':
        return '测试用户';
      case 'demo':
        return '演示用户';
      default:
        return username;
    }
  }

  /// 根据用户名获取科室
  String _getDepartmentByUsername(String username) {
    switch (username) {
      case 'admin':
        return '信息科';
      case 'doctor':
        return '内科';
      case 'nurse':
        return '护理部';
      default:
        return '综合科';
    }
  }

  /// 根据用户名获取职位
  String _getPositionByUsername(String username) {
    switch (username) {
      case 'admin':
        return '系统管理员';
      case 'doctor':
        return '主治医师';
      case 'nurse':
        return '护士长';
      default:
        return '医护人员';
    }
  }

  /// 模拟登录
  Future<void> _mockLogin(String username, String password) async {
    // 模拟网络延迟
    await Future.delayed(const Duration(seconds: 1));

    // 模拟登录验证
    if (username == 'admin' && password == '123456') {
      // 保存登录状态
      await globalConfig.setBool('is_logged_in', true);
      await globalConfig.setString('current_username', username);

      // 保存凭据（如果选择记住密码）
      if (isRememberPassword.value) {
        await globalConfig.setString('saved_username', username);
        await globalConfig.setString('saved_password', password);
        await globalConfig.setBool('remember_password', true);
      } else {
        await globalConfig.remove('saved_password');
        await globalConfig.setBool('remember_password', false);
      }

      Fluttertoast.showToast(msg: '登录成功');

      // 跳转到主页面
      Get.offAllNamed(RouterIdConfig.root);
    } else {
      Fluttertoast.showToast(msg: '用户名或密码错误');
    }
  }

  /// 忘记密码点击事件
  void onForgotPasswordTap() {
    // TODO: 跳转到忘记密码页面
    // Get.toNamed(RouterIdConfig.forgotPassword);
    Fluttertoast.showToast(msg: '忘记密码功能暂未开放');
  }

  /// 注册点击事件
  void onRegisterTap() {
    _showRegisterDialog();
  }

  /// 显示注册对话框
  void _showRegisterDialog() {
    final usernameController = TextEditingController();
    final passwordController = TextEditingController();
    final confirmPasswordController = TextEditingController();
    final nicknameController = TextEditingController();
    final phoneController = TextEditingController();
    final isLoading = false.obs;

    Get.dialog(
      AlertDialog(
        title: const Text('用户注册'),
        content: SizedBox(
          width: 300,
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              TextField(
                controller: usernameController,
                decoration: const InputDecoration(
                  labelText: '用户名',
                  hintText: '请输入用户名',
                ),
              ),
              const SizedBox(height: 16),
              TextField(
                controller: nicknameController,
                decoration: const InputDecoration(
                  labelText: '昵称',
                  hintText: '请输入昵称',
                ),
              ),
              const SizedBox(height: 16),
              TextField(
                controller: phoneController,
                decoration: const InputDecoration(
                  labelText: '手机号',
                  hintText: '请输入手机号',
                ),
                keyboardType: TextInputType.phone,
              ),
              const SizedBox(height: 16),
              TextField(
                controller: passwordController,
                decoration: const InputDecoration(
                  labelText: '密码',
                  hintText: '请输入密码（至少6位）',
                ),
                obscureText: true,
              ),
              const SizedBox(height: 16),
              TextField(
                controller: confirmPasswordController,
                decoration: const InputDecoration(
                  labelText: '确认密码',
                  hintText: '请再次输入密码',
                ),
                obscureText: true,
              ),
            ],
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Get.back(),
            child: const Text('取消'),
          ),
          Obx(() => TextButton(
                onPressed: isLoading.value
                    ? null
                    : () async {
                        final username = usernameController.text.trim();
                        final password = passwordController.text.trim();
                        final confirmPassword =
                            confirmPasswordController.text.trim();
                        final nickname = nicknameController.text.trim();
                        final phone = phoneController.text.trim();

                        // 验证输入
                        if (username.isEmpty ||
                            password.isEmpty ||
                            confirmPassword.isEmpty ||
                            nickname.isEmpty ||
                            phone.isEmpty) {
                          Fluttertoast.showToast(msg: '请填写完整信息');
                          return;
                        }

                        if (password.length < 6) {
                          Fluttertoast.showToast(msg: '密码长度不能少于6位');
                          return;
                        }

                        if (password != confirmPassword) {
                          Fluttertoast.showToast(msg: '两次输入的密码不一致');
                          return;
                        }

                        // 手机号格式验证
                        if (!RegExp(r'^1[3-9]\d{9}$').hasMatch(phone)) {
                          Fluttertoast.showToast(msg: '请输入正确的手机号');
                          return;
                        }

                        try {
                          isLoading.value = true;

                          // 模拟网络延迟
                          await Future.delayed(
                              const Duration(milliseconds: 500));

                          // 检查用户名是否已存在（从本地存储的注册用户列表中检查）
                          final registeredUsers =
                              SharedPreferencesTool.getStringList(
                                      'registered_users') ??
                                  [];
                          if (registeredUsers.contains(username)) {
                            Fluttertoast.showToast(msg: '用户名已存在');
                            return;
                          }

                          // 保存新用户到本地存储
                          registeredUsers.add(username);
                          await SharedPreferencesTool.putStringList(
                              'registered_users', registeredUsers);

                          // 保存用户密码（实际项目中应该加密存储）
                          await SharedPreferencesTool.putString(
                              'user_password_$username', password);

                          // 保存用户详细信息
                          final userInfo = {
                            'id':
                                'user_${username}_${DateTime.now().millisecondsSinceEpoch}',
                            'username': username,
                            'nickname': nickname,
                            'phone': phone,
                            'avatar':
                                'https://api.dicebear.com/7.x/avataaars/svg?seed=$username',
                            'email': '$username@medical.com',
                            'department': '综合科',
                            'position': '医护人员',
                            'createTime': DateTime.now().toIso8601String(),
                          };
                          await SharedPreferencesTool.putString(
                              'user_info_$username', jsonEncode(userInfo));

                          Fluttertoast.showToast(msg: '注册成功');
                          Get.back();
                          // 自动填充用户名
                          this.usernameController.text = username;
                        } catch (e) {
                          debugPrint('注册失败: $e');
                          Fluttertoast.showToast(msg: '注册失败，请重试');
                        } finally {
                          isLoading.value = false;
                        }
                      },
                child: isLoading.value
                    ? const SizedBox(
                        width: 16,
                        height: 16,
                        child: CircularProgressIndicator(strokeWidth: 2),
                      )
                    : const Text('注册'),
              )),
        ],
      ),
    );
  }

  /// 游客登录点击事件
  Future<void> onGuestLoginTap() async {
    try {
      isLoading.value = true;

      // 模拟网络延迟
      await Future.delayed(const Duration(milliseconds: 500));

      // 设置游客登录状态
      await SharedPreferencesTool.putBool('is_logged_in', true);
      await SharedPreferencesTool.putBool('is_guest_mode', true);
      await SharedPreferencesTool.putString('current_username', '游客');
      await SharedPreferencesTool.putString(
          'current_user_id', 'guest_${DateTime.now().millisecondsSinceEpoch}');
      await SharedPreferencesTool.putString('current_token',
          'guest_token_${DateTime.now().millisecondsSinceEpoch}');

      // 保存游客用户信息
      final guestUserInfo = {
        'id': 'guest_${DateTime.now().millisecondsSinceEpoch}',
        'username': '游客',
        'nickname': '游客用户',
        'avatar': 'https://api.dicebear.com/7.x/avataaars/svg?seed=guest',
        'phone': '',
        'email': '',
        'department': '',
        'position': '游客',
        'createTime': DateTime.now().toIso8601String(),
      };
      await SharedPreferencesTool.saveUserInfo(guestUserInfo);

      Fluttertoast.showToast(msg: '游客登录成功');

      // 跳转到主页面
      Get.offAllNamed(RouterIdConfig.root);
    } catch (e) {
      debugPrint('游客登录失败: $e');
      Fluttertoast.showToast(msg: '登录失败，请重试');
    } finally {
      isLoading.value = false;
    }
  }

  /// 清除输入
  void clearInput() {
    usernameController.clear();
    passwordController.clear();
    isPasswordHidden.value = true;
    isRememberPassword.value = false;
  }
}
